from datetime import datetime

from models import Borrow, BorrowVO, Book, db, ReturnVO
from common.response import Response

from util.jsonUtil import borrow2dict, response2dict, book2dict, borrowVO2dict, returnVO2dict


#查询所有borrow记录
def getAllBorrowList():
    borrowList = Borrow.query.all()
    borrowVOList = []
    for borrow in borrowList:
        book = Book.query.get(borrow.book_id)
        borrowVO = BorrowVO(borrow, book)
        borrowVOList.append(borrowVO)
    code = "200"
    msg = "查询成功"
    data = [borrowVO2dict(borrowVO1) for borrowVO1 in borrowVOList]
    response = Response(code, msg, data)
    return response2dict(response)


#根据userID查询借阅记录
def getBorrowByuserId(userid):
    borrowList = Borrow.query.filter_by(user_id=userid).all()
    borrowVOList = []

    if borrowList:
        for borrow in borrowList:
            book = Book.query.get(borrow.book_id)
            borrowVO = BorrowVO(borrow, book)
            borrowVOList.append(borrowVO)
        code = "200"
        msg = '获取成功'
        data = [borrowVO2dict(borrowVO1) for borrowVO1 in borrowVOList]
        response = Response(code, msg, data)

    else:
        code = "404"
        msg = '获取失败，没有该userid的用户'
        data = ''
        response = Response(code, msg, data)

    return response2dict(response)


#添加借阅记录
def addNewBorrow(borrow, bookid):
    print(bookid)
    book = Book.query.get(bookid)
    print(book.num)
    book.num = book.num - borrow.num
    if book.num>=0:
        db.session.add(borrow)
        db.session.commit()
        borrowVO = BorrowVO(borrow, book)
        code = "200"
        msg = '借阅成功'
        data = borrowVO2dict(borrowVO)
        response = Response(code, msg, data)
        return response2dict(response)
    else:
        book.num = 0
        borrowVO = BorrowVO(borrow, book)
        code = "200"
        msg = '借阅失败，该书已被借完'
        data = ""
        response = Response(code, msg, data)
        return response2dict(response)
#删除借阅记录
def deleteBorrow(user_id, book_id):
    borrow = Borrow.query.filter_by(user_id=user_id).filter_by(book_id=book_id).first()
    book = Book.query.get(book_id)
    db.session.delete(borrow)
    db.session.commit()
    code = "200"
    msg = '删除成功'
    borrowVO = BorrowVO(borrow, book)
    data = borrowVO2dict(borrowVO)
    response = Response(code, msg, data)
    return response2dict(response)


#归还
def addNewReturn(borrow_r, bookid):
    print(borrow_r.id)
    borrow = Borrow.query.get(borrow_r.id)
    print(borrow)
    borrow_r.borrow_time = borrow.borrow_time
    date = datetime.now()
    borrow_r.return_time = date
    db.session.delete(borrow)
    db.session.commit()
    db.session.add(borrow_r)
    db.session.commit()
    print(bookid)
    book = Book.query.get(bookid)
    print(book.num)
    book.num = book.num + borrow.num
    returnVO = ReturnVO(borrow_r, book)
    code = "200"
    msg = '归还成功'
    data = returnVO2dict(returnVO)
    response = Response(code, msg, data)
    return response2dict(response)
